import i18n from "../../i18n/i18n"
import {applyMiddleware, combineReducers, createStore} from "redux";
import {connect} from "react-redux";
import reduxPromise from "redux-promise";
import coreReducer from "../reducer";
import Config from "../Config";
import {isFunction} from "./TypeUtil";

let store: any, dispatch: any;
const initStore: Function = (): any => {
    if (store) {
        throw new Error(i18n.t("unManyInit"));
    }

    let reducers: object = {
        [Config.storeKey]: coreReducer
    };

    store = createStore(combineReducers(reducers), {}, applyMiddleware(reduxPromise));

    dispatch = store.dispatch;

    return store
};

initStore();

// @ts-ignore
const coreConnect: Function = (...reducerList: string[]) => {
    return connect((store: any) => {
        let reducers: object[] = store[Config.storeKey];
        let state: object = {};
        for (let index: number = 0; index < reducerList.length; index++) {
            let key: string = reducerList[index];
            // @ts-ignore
            state = {...state, ...reducers[key]}
        }
        return state
    })
};

// @ts-ignore
const coreDispatch: Function = async (type: string, payload: any) => {
    let result: any = isFunction(payload) ? (await payload()) : (payload || {});
    dispatch({
        type: type,
        payload: result
    })
};

export {
    store,
    coreConnect,
    coreDispatch
};